// pages/poster/poster.js
var api = require("../../utils/api.js");
var util = require("../../utils/util.js");
import Poster from '../../canvas/poster/poster';

const app = getApp();
var pixelRatio = 2;
var imgWidth = 750;
var imgHeight = 1334;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    imgs: null,
    sort: 0,
    step: 0,
    qrCode: '../../res/qr_code_test.png',
    index: 0,
    shareImage: '',
    posterConfig: {},
    pixelRatio: 2,
    header: null,
    posterImg: null,
  },

  change: function (e) {
    this.setData({
      index: e.detail.current,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.shareBack) {
      this.setData({
        imgs: app.globalData.shareBack,
      })
      this.getShareBack();
    } else {
      app.shareBackCallback = res => {
        this.setData({
          imgs: res,
        })
        this.getShareBack();
      }
    }

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
      })
    } else {
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: app.globalData.userInfo,
        })
      }
    }

    if (app.globalData.qrCode) {
      this.setData({
        qrCode: app.globalData.qrCode,
      })
    } else {
      app.qrCodeCallback = res => {
        this.setData({
          qrCode: res,
        })
      }
    }
  },
  //获得分享背景信息
  getShareBack: function () {
    api.getShareBack((img, sort, step) => {
      app.globalData.shareBack = img;
      this.setData({
        imgs: img,
        sort: sort,
        step: step,
      })
    });
  },
  //保存图片
  saveImage: function (e) {
    var url = this.data.userInfo.avatarUrl;
    if (this.data.header) {
      this.downloadPoster();
    } else {
      wx.showLoading({})
      wx.downloadFile({
        url: url,
        success: res => {
          wx.hideLoading();
          this.setData({
            header: res.tempFilePath,
          })
          this.downloadPoster();
        },
        fail: res => {
          wx.hideLoading();
          this.onPosterFail();
        }
      })
    }


  },
  //下载海报
  downloadPoster: function () {
    var url = this.data.imgs[this.data.index];

    wx.showLoading();
    wx.downloadFile({
      url: url,
      success: res => {
        wx.hideLoading();
        this.setData({
          posterImg: res.tempFilePath,
        })
        this.initPoster();
      },
      fail: res => {
        wx.hideLoading();
        this.onPosterFail();
      }
    })
  },

  initPoster: function () {
    wx.getImageInfo({
      src: this.data.posterImg,
      success: res => {
        imgWidth = res.width;
        imgHeight = res.height;
        this.setData({
          posterConfig: this.updatePosterConfig()
        }, () => {
          Poster.create(true); // 入参：true为抹掉重新生成 
        });
      },
      fail: function (err) {
        this.onPosterFail();
      },
    })
  },

  rpxToPx: function (rpx) {
    return rpx * pixelRatio;
  },

  updatePosterConfig: function () {
    try {
      const system = wx.getSystemInfoSync()
      pixelRatio = system.pixelRatio;
      var width = system.windowWidth;
      var height = system.windowWidth / imgWidth * imgHeight;
      // console.log(width+''+height);
      // console.log(this.data.userInfo.avatarUrl);
      // console.log(this.data.imgs[this.data.index]);
      return {
        width: this.rpxToPx(width),
        height: this.rpxToPx(height),
        backgroundColor: '#fff',
        debug: false,
        images: [{
            width: this.rpxToPx(width),
            height: this.rpxToPx(height),
            x: 0,
            y: 0,
            url: this.data.posterImg,
          },
          {
            width: this.rpxToPx(72),
            height: this.rpxToPx(72),
            x: this.rpxToPx(36),
            y: this.rpxToPx(height - 164),
            url: this.data.header,
          },
          {
            width: this.rpxToPx(72),
            height: this.rpxToPx(72),
            x: this.rpxToPx(width - 108),
            y: this.rpxToPx(height - 164),
            url: this.data.qrCode,
          },
        ],
        blocks: [{
          width: this.rpxToPx(width - 48),
          height: this.rpxToPx(96),
          x: this.rpxToPx(24),
          y: this.rpxToPx(height - 176),
          borderRadius: this.rpxToPx(16),
          backgroundColor: '#fff',
        }, ],
        texts: [{
            x: this.rpxToPx(116),
            y: this.rpxToPx(height - 164),
            fontSize: this.rpxToPx(14),
            text: this.data.userInfo.nickName,
            lineNum: 1,
            baseLine: 'top',
            color: '#000',
            zIndex: 1,
          },
          {
            x: this.rpxToPx(116),
            y: this.rpxToPx(height - 144),
            fontSize: this.rpxToPx(10),
            text: '达人步兑',
            lineNum: 1,
            baseLine: 'top',
            color: '#666',
            zIndex: 1,
          },
          {
            x: this.rpxToPx(116),
            y: this.rpxToPx(height - 112),
            zIndex: 1,
            text: [{
                text: '今日总步数',
                fontSize: this.rpxToPx(10),
                color: '#666',
                lineNum: 1,
              },
              {
                text: this.data.step,
                fontSize: this.rpxToPx(16),
                fontWeight: 'bold',
                color: '#56a647',
                marginLeft: 8,
                marginRight: 8,
                lineNum: 1,
              },
              {
                text: '步',
                fontSize: this.rpxToPx(10),
                color: '#666',
                lineNum: 1,
              },
            ],
          },
          {
            x: this.rpxToPx(116),
            y: this.rpxToPx(height - 106),
            fontSize: this.rpxToPx(10),
            text: '排名第' + this.data.sort + "名，请送我上去",
            lineNum: 1,
            baseLine: 'top',
            color: '#666',
            zIndex: 1,
          },
        ],
      }
    } catch (e) {
      this.onPosterFail();
    }
  },

  //海报生成成功
  onPosterSuccess(e) {
    const {
      detail
    } = e;
    wx.previewImage({
      current: detail,
      urls: [detail]
    })

    // console.log(detail);
    wx.saveImageToPhotosAlbum({
      filePath: detail,
      success(result) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
      }
    })

  },
  //失败
  onPosterFail(err) {
    wx.showToast({
      title: '生成图片失败！',
      icon: 'fail'
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.shareSeekHelp(util.sponsorPath(app.globalData.userStatus.open_id));
  }
})